package com.xx.doublexchat.common.user.event.listener;

import com.xx.doublexchat.common.user.cache.UserCache;
import com.xx.doublexchat.common.user.dao.UserDao;
import com.xx.doublexchat.common.user.domain.entity.User;
import com.xx.doublexchat.common.user.event.UserBlackEvent;
import com.xx.doublexchat.common.user.service.IUserBackpackService;
import com.xx.doublexchat.common.websocket.service.WebSocketService;
import com.xx.doublexchat.common.websocket.service.adapter.WebSocketAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

/**
 * 用户注册事件监听者
 */
@Component
public class UserBlackListener {

    @Autowired
    private UserDao userDao;

    @Autowired
    private WebSocketService webSocketService;

    @Autowired
    private UserCache userCache;

    /**
     * 拉黑用户吗，发送消息给所有用户
     * 监听用户注册事件, 事务提交后执行
     *
     * @param event
     */
    @Async
    @TransactionalEventListener(classes = UserBlackEvent.class, phase = TransactionPhase.AFTER_COMMIT)
    public void sendMsg(UserBlackEvent event) {
        User user = event.getUser();
        //发送消息给所有用户
        webSocketService.sendMsgToAll((WebSocketAdapter.buildBlack(user)));
    }

    /**
     * 更新状态
     *
     * @param event
     */
    @Async
    @TransactionalEventListener(classes = UserBlackEvent.class, phase = TransactionPhase.AFTER_COMMIT)
    public void changeUserStatus(UserBlackEvent event) {
        //拉黑用户
        userDao.invalidUid(event.getUser().getId());
    }

    /**
     * 清除缓存
     * @param event
     */
    @Async
    @TransactionalEventListener(classes = UserBlackEvent.class, phase = TransactionPhase.AFTER_COMMIT)
    public void evictCache(UserBlackEvent event) {
        //清除拉黑用户缓存
        userCache.evictBlackMap();
    }

}
